<template>
  <div class="main">
    <!-- 面包屑：导航 -->
    <app-link :name="title"></app-link>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-input
          type="number"
          v-model="searchForm.goodprice"
          placeholder="价格"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.goodsStar" placeholder="评价">
          <el-option label="★" value="★"></el-option>
          <el-option label="★★" value="★★"></el-option>
          <el-option label="★★★" value="★★★"></el-option>
          <el-option label="★★★★" value="★★★★"></el-option>
          <el-option label="★★★★★" value="★★★★★"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="termSearch" icon="el-icon-search"
          >查询</el-button
        >
        <el-button type="primary" @click="reset" icon="el-icon-refresh-left"
          >重置</el-button
        >
        <el-button type="primary" @click="addGood" icon="el-icon-document"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 商品列表页:border加边框，stripe：斑马纹 -->
    <el-table :data="list" border style="width: 100%" height="500px" stripe>
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="_id" label="商品号" width="150"></el-table-column>
      <el-table-column
        prop="goodname"
        label="商品名"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="goodprice"
        label="商品价格"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="storename"
        label="店铺名"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="goodsStar"
        label="商品评价等级"
        width="150"
      ></el-table-column>
      <el-table-column label="商品图" width="80">
        <template slot-scope="scope">
          <!-- scope指整个数据对象。scope.row指当前行数据 -->
          <img :src="scope.row.img" alt style="width:50px;height:50px;" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="editGood(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="delGood(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="pages > 1"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog
      :title="isAdd ? '添加商品' : '编辑商品'"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form
        :rules="rules"
        :model="ruleForm"
        label-position="right"
        label-width="100px"
        class="demo-ruleForm"
        ref="ruleForm"
      >
        <el-form-item label="商品名" prop="goodname">
          <el-input
            v-model="ruleForm.goodname"
            autocomplete="off"
            placeholder="请输入商品名"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="goodprice">
          <el-input
            v-model="ruleForm.goodprice"
            autocomplete="off"
            placeholder="请输入价格"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="店铺名" prop="storename">
          <el-input
            v-model="ruleForm.storename"
            autocomplete="off"
            placeholder="请输入店铺名"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <!-- 商品评价 -->
        <el-form-item label="商品评价" prop="goodsStar">
          <el-select v-model="ruleForm.goodsStar" placeholder="选择星级">
            <el-option label="★" value="★"></el-option>
            <el-option label="★★" value="★★"></el-option>
            <el-option label="★★★" value="★★★"></el-option>
            <el-option label="★★★★" value="★★★★"></el-option>
            <el-option label="★★★★★" value="★★★★★"></el-option>
          </el-select>
        </el-form-item>
        <!-- 上传文件 -->
        <el-form-item prop="img" label="上传头像">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="/dev-api/goodMgr/addGood"
            :file-list="fileList"
            :http-request="httpRequest"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="onChange"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            multiple
            :limit="1"
            name="photo"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="isAdd ? add() : edit()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import appLink from "@/components/link";
import goodsApi from "@/api/goodsApi";

export default {
  data() {
    return {
      title: "商品管理",
      searchForm: {},
      list: [],
      page: 1,
      pagesize: 10,
      total: 0,
      pages: 0,
      dialogFormVisible: false,
      rules: {
        goodname: [
          { required: true, message: "商品名不能为空", trigger: "blur" },
        ],
        goodprice: [
          { required: true, message: "价格不能为空", trigger: "blur" },
        ],
        storename: [
          { required: true, message: "店铺名不能为空", trigger: "blur" },
        ],
        goodsStar: [
          { required: true, message: "评价星级不能为空", trigger: "blur" },
        ],
      },
      ruleForm: {
        goodname: "",
        goodprice: "" * 1,
        storename: "",
        goodsStar: "",
      },
      isAdd: true,
      fileList: [],
    };
  },
  components: {
    appLink,
  },
  methods: {
    async searchAll() {
      try {
        let query = JSON.stringify(this.searchForm);
        let res = await goodsApi.getGoodsList(this.page, this.pagesize, query);
        if (res.data.flag) {
          this.list = res.data.data; //数据部分
          this.total = res.data.total; //总条数
          this.pages = res.data.totalPages;
        } else {
          this.$message({
            message: "找不到该数据哦，换个条件试试",
            type: "warnning",
          });
        }
      } catch (error) {}
    },

    reset() {
      this.searchForm = {};
    },
    //条件查询
    termSearch() {
      this.page = 1;
      this.pagesize = 10;
      if (this.searchForm.goodprice) {
        this.searchForm.goodprice = this.searchForm.goodprice * 1;
      }
      this.searchAll();
    },
    //功能：点击打开新增弹窗
    addGood() {
      this.isAdd = true; //添加用户，开关设置为true
      this.dialogFormVisible = true;
      this.fileList = [];
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["ruleForm"].resetFields();
      });
    },
    //点击编辑按钮
    editGood(row) {
      console.log(row, "edit");
      this.isAdd = false; //编辑弹窗设置为false
      this.dialogFormVisible = true; //点击打开弹窗
      this.ruleForm = row;
      this.fileList = [];
      console.log(this.ruleForm);

      let obj = {
        name: this.ruleForm.fileNames,
        url: this.ruleForm.img,
      };
      this.fileList.push(obj);
    },
    //点击删除按钮
    delGood(row) {
      this.$confirm("此操作将永久删除该用户吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //点击确定：真的删除
          goodsApi.delGood(row._id).then((res) => {
            if (res.data.flag) {
              //删除成功
              this.$message({
                message: "删除成功",
                type: "success",
              });

              //刷新页面
              this.searchAll();
            } else {
              //修改失败
              this.$message({
                message: "删除失败",
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //添加商品
    add() {
      this.$refs.ruleForm.validate(async (res) => {
        if (res) {
          //正则校验通过：运行上传数据添加新用户
          let form = new FormData();
          form.append("goodname", this.ruleForm.goodname);
          form.append("goodprice", this.ruleForm.goodprice * 1);
          form.append("storename", this.ruleForm.storename);
          form.append("goodsStar", this.ruleForm.goodsStar);
          form.append("gooddetail", "暂无商品详情噢");
          this.fileList.forEach((file) => {
            form.append("photo", file.raw); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
            form.append("fileNames", file.name);
          });
          // 调用接口
          try {
            let p = await goodsApi.addGoods(form);
            console.log(p.data);
            if (p.data.flag) {
              //提交成功
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.dialogFormVisible = false; //关闭弹窗
            } else {
              this.$message({
                message: "添加失败",
                type: "error",
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          //校验没通过：不能提交
          this.$message({
            message: "注意书写条件哦",
            type: "error",
          });
        }
      });
    },
    //编辑商品
    edit() {
      let form = new FormData();
      form.append("goodname", this.ruleForm.goodname);
      form.append("goodprice", this.ruleForm.goodprice * 1);
      form.append("storename", this.ruleForm.storename);
      form.append("goodsStar", this.ruleForm.goodsStar);
      form.append("_id", this.ruleForm._id);
      this.fileList.forEach((file) => {
        //接口那边：req.files
        form.append("photo", file.raw); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
        form.append("fileNames", file.name);
      });
      goodsApi.editGood(form).then((res) => {
        // console.log(res.data);
        if (res.data.flag) {
          //修改成功
          this.$message({
            message: "修改成功",
            type: "success",
          });

          //关闭弹窗并刷新页面
          this.dialogFormVisible = false;
          this.searchAll();
        } else {
          //修改失败
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },

    //功能：分页功能1
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val; //每页多少条
      this.page = 1; //如果切换每页多少条，回到第一页开始看
      this.searchAll();
    },

    //功能：分页功能2
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.searchAll();
    },

    // 文件上传相关
    //功能：文件上传(上传头像)
    httpRequest(file) {
      // console.log(file, 111);
    },
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    //功能：删除已上传图片
    handleRemove(file, fileList) {
      //删除文件
      console.log(file, fileList, 222);
      let url = file.url;
      console.log(url, this.ruleForm._id, 789);
    },
    handlePreview(file) {
      console.log(file, 333);
    },
    //功能：选择图片超过规定提示
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    //功能：删除图片前提示
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },

  created() {
    this.searchAll();
  },
};
</script>

<style>
.el-form {
  margin-top: 20px;
}
.el-pagination {
  text-align: center;
  margin-top: 30px;
}
.el-pagination .el-pager li {
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #ccc;
  margin-right: 5px;
}
.el-pagination .el-pager .active {
  background: #58bc58;
  color: #fff;
  cursor: pointer;
}
</style>
